package com.qfedu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 概述:
 *
 * @Author: Tbh
 * @Date: 2022/7/2 10:14
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userDetailsService;

    // 配置用户service和密码加密器，进行登录认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭默认资源拦截
        http.csrf().disable();


        http
                // 自定义表单登录
                .formLogin()
                // 登录页面
                .loginPage("/login.html")
                // 登录访问路径，表单路径
                .loginProcessingUrl("/login")
                // 登录成功   放行
                .defaultSuccessUrl("/index.html").permitAll()
                // 登录失败
                .failureUrl("/error.html")
                .and()
                // 认证配置
                .authorizeRequests()
                .antMatchers("/login.html", "/login").permitAll()  //permitAll() 无条件允许访问 , "/project/**"
                //配置静态页面可以访问
                .antMatchers("/js/**", "/css/**", "/img/**", "/images/**", "/favicon.ico").permitAll();


        // 认证通过之后全部放行（不拦截）
        http.authorizeRequests()
                .anyRequest()
                .authenticated();


        // 运行页面iframe操作
        http.headers().frameOptions().sameOrigin();
    }
}
